package org.polyforms.repository.executor.support;

import java.util.List;

import javax.inject.Named;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

/**
 * Implementation of get method which returns one matching entity or null if no matching.
 * 
 * NonUniqueResultException throws if more than one entities matching searching criteria.
 * 
 * @author Kuisong Tong
 * @since 1.0
 */
@Named
public final class GetExecutor extends QueryExecutor {
    /**
     * {@inheritDoc}
     */
    @Override
    protected Object getResult(final Query query) {
        final List<?> resultList = query.getResultList();
        if (resultList.isEmpty()) {
            return null;
        }

        if (resultList.size() > 1) {
            throw new NonUniqueResultException("Too many rows found: " + resultList.size());
        }

        return resultList.get(0);
    }

    /**
     * {@inheritDoc}
     */
    public String[] getPrefixes() {
        return new String[] { "get" };
    }
}
